package com.symaster.swingalixcomponent.icon;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;

/**
 * @author yinmiao
 * @version 2024/2/26
 */
public class RotateIcon extends JComponent {

    private ImageIcon icon;
    private Image image;
    private float angle;
    private float angleOffset;

    public RotateIcon() {
    }

    public RotateIcon(ImageIcon icon) {
        this.icon = icon;
        this.image = icon.getImage();
    }

    public ImageIcon getIcon() {
        return icon;
    }

    public void setIcon(ImageIcon icon) {
        this.icon = icon;
        if (icon != null) {
            this.image = icon.getImage();
        } else {
            this.image = null;
        }
    }

    public float getAngle() {
        return angle;
    }

    public void setAngle(float angle) {
        this.angle = angle;
    }

    public float getAngleOffset() {
        return angleOffset;
    }

    public void setAngleOffset(float angleOffset) {
        this.angleOffset = angleOffset;
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(image.getWidth(null), image.getHeight(null));
    }

    @Override
    public void paint(Graphics g) {
        if (image != null) {
            int imgW = image.getWidth(null);
            int imgH = image.getHeight(null);

            Graphics2D g2d = (Graphics2D) g;
            g2d.transform(AffineTransform.getRotateInstance(
                    (angle + angleOffset) * (Math.PI / 180),
                    getWidth() / 2f, getHeight() / 2f));
            g2d.drawImage(image, Math.round(getWidth() / 2f - imgW / 2f), Math.round(getHeight() / 2f - imgH / 2f), null);
        }
    }
}
